import { defineStore } from 'pinia'
import { ref } from 'vue'

interface User {
  id: number
  username: string
  email: string
  token: string
}

interface RegisterForm {
  username: string
  email: string
  password: string
  confirmPassword: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)

  // 从本地存储加载用户信息
  const loadUserFromStorage = () => {
    const storedUser = localStorage.getItem('user')
    const storedToken = localStorage.getItem('token')
    
    if (storedUser) {
      user.value = JSON.parse(storedUser)
    }
    
    if (storedToken) {
      token.value = storedToken
    }
  }

  // 初始加载用户信息
  loadUserFromStorage()

  // 判断是否已登录
  const isLoggedIn = () => !!token.value

  // 模拟登录方法（实际项目中应该调用API）
  const login = async (username: string, password: string) => {
    // 这里应该是实际的API调用
    // 模拟API调用
    return new Promise<void>((resolve, reject) => {
      // 模拟成功响应
      setTimeout(() => {
        // 实际项目中，这些数据应该来自后端
        const userData: User = {
          id: 1,
          username,
          email: 'user@example.com',
          token: 'mock-jwt-token'
        }
        
        // 更新状态
        user.value = userData
        token.value = userData.token
        
        // 存储到本地
        localStorage.setItem('user', JSON.stringify(userData))
        localStorage.setItem('token', userData.token)
        
        resolve()
      }, 1000)
    })
  }

  // 模拟注册方法
  const register = async (form: RegisterForm) => {
    // 这里应该是实际的API调用
    return new Promise<void>((resolve, reject) => {
      // 模拟成功响应
      setTimeout(() => {
        // 实际项目中，这些应该由后端处理
        resolve()
      }, 1000)
    })
  }

  // 退出登录
  const logout = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }

  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout
  }
}) 